package com.google.code.bbdsm.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import blackboard.platform.context.Context;
import blackboard.platform.security.Entitlement;
import blackboard.platform.security.Entitlements;



/*
 * Check if the current user has a certain entitlement.
 * Redirect him to a certain page if he doesn't.
 */
public class EntitlementsCheckerInterceptor  extends HandlerInterceptorAdapter {

	protected String requiredEntitlementUid;
	
	protected String requestAttributeKeyForBbContext;
	
	protected String failureRedirectUrl;
	
	protected Log logger = LogFactory.getLog(getClass());
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
		Context bbContext = (Context) request.getAttribute(requestAttributeKeyForBbContext);
		Entitlements entitlements = bbContext.getEntitlements();
		Entitlement requiredEntitlement = new Entitlement();
		requiredEntitlement.setEntitlementUid(requiredEntitlementUid);
		
		if(entitlements.has(requiredEntitlement))
			return true;
		response.sendRedirect(failureRedirectUrl);
		return false;
	}

	public String getRequestAttributeKeyForBbContext() {
		return requestAttributeKeyForBbContext;
	}

	public void setRequestAttributeKeyForBbContext(
			String requestAttributeKeyForBbContext) {
		this.requestAttributeKeyForBbContext = requestAttributeKeyForBbContext;
	}

	public String getRequiredEntitlementUid() {
		return requiredEntitlementUid;
	}

	public void setRequiredEntitlementUid(String requiredEntitlementUid) {
		this.requiredEntitlementUid = requiredEntitlementUid;
	}

	public String getFailureRedirectUrl() {
		return failureRedirectUrl;
	}

	public void setFailureRedirectUrl(String failureRedirectUrl) {
		this.failureRedirectUrl = failureRedirectUrl;
	}

}
